import React, { useState, useEffect } from "react";
import { Button, Modal, message, Upload, Progress, Result } from "antd";
import { FormSelect } from "@/components";
import ajax from "@/config/ajax";
import excelImg from "@/assets/images/excel.png";
import "./index.scss";
const { Dragger } = Upload;

function UploadModal(props) {
  const {
    visible,
    chartTypeOptions = [],
    onCancel = () => {}, // 弹窗关闭
    onSuccess = () => {}, // 上传成功
  } = props;

  const [formData, setFormData] = useState({
    chart_type: "",
  });
  const uploadAccept = ".xls,.xlsx,.csv";
  const [accept, setAccept] = useState([uploadAccept]);

  const [percent, setPercent] = useState(0);
  const [isShowRes, setIsShowRes] = useState(1);
  const [result, setResult] = useState({
    status: "success",
    title: "导入文件成功",
  });

  const uploadProps = {
    accept: accept,
    multiple: false,
    showUploadList: false,
    action: "",
    beforeUpload: (file) => {
      if (!formData.chart_type) {
        message.warning("请先选择要上传的图标类型");
        return;
      }
      if (!file.size) {
        message.warning(`${file.name}文件大小为0`);
        return;
      }
      let fileInfo = {
        name: file.name,
        size: file.size,
        sizeText: "",
        state: "uploading",
        file: file,
      };
      handleUpload(fileInfo);
      return false;
    },
  };

  const handleError = (msg) => {
    message.error(msg || "服务器异常");
    setIsShowRes(3);
    setResult({ status: "error", title: "文件导入失败" });
  };

  const handleUpload = (fileInfo) => {
    let file = fileInfo;
    if (file.size) {
      let _file = file.file;
      let fileInfo = JSON.parse(JSON.stringify(file));
      fileInfo.file = _file;

      let checkData = new FormData();
      checkData.append("file", fileInfo.file);
      checkData.append("chart_type", formData.chart_type);
      setPercent(0);
      setIsShowRes(2);
      ajax({
        url: "/carbon/api/file/upload",
        type: "POST",
        data: checkData,
      })
        .then((res) => {
          if (res.code === 200) {
            setPercent(100);
            setTimeout(() => {
              setIsShowRes(3);
              setResult({ status: "success", title: "文件导入成功" });
              onSuccess(res);
            }, 500);
          } else {
            handleError(res.message);
          }
        })
        .catch((err) => {
          handleError();
        });
    }
  };

  const onClose = () => {
    onCancel(result.status === "success");
    setFormData({ chart_type: "" });
    setIsShowRes(1);
  };
  const resultProps = {
    ...result,
    extra:
      result.status === "success" ? (
        <Button type="primary" onClick={onClose}>
          确认
        </Button>
      ) : (
        [
          <Button
            type="primary"
            onClick={() => {
              setIsShowRes(1);
              setFormData({ chart_type: "" });
            }}
          >
            重新上传
          </Button>,
          <Button onClick={onClose}>关闭</Button>,
        ]
      ),
  };

  return (
    <Modal
      className="upload-modal adm-modal"
      title="导入"
      visible={visible}
      maskClosable={false}
      onCancel={onClose}
      footer={null}
    >
      {isShowRes === 1 ? (
        <div className="content">
          <FormSelect
            className="form-item"
            admLabel="图表类型"
            labelPosition="left"
            isRequired={true}
            value={formData.chart_type}
            options={chartTypeOptions}
            onChange={(v, option) => {
              setFormData({ ...formData, chart_type: option.children });
              setAccept(v === "0" ? ".*" : uploadAccept);
            }}
          />
          <Dragger {...uploadProps}>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                flexDirection: "column",
              }}
            >
              <p style={{ textAlign: "center" }}>
                <img
                  style={{ width: "102px", width: "68px" }}
                  src={excelImg}
                  alt=""
                />
              </p>
              <p style={{ fontSize: "18px" }}>点击拖拽Excel表格到此处</p>
              <p className="warning-more">* 请使用标准模板上传数据</p>
            </div>
          </Dragger>
        </div>
      ) : null}
      {isShowRes === 2 ? (
        <div className="progress">
          <p>
            正在导入...{" "}
            <span style={{ color: "#ef5454" }}>（请勿关闭弹窗）</span>
          </p>
          <Progress size="large" percent={percent} showInfo={false} />
        </div>
      ) : null}
      {isShowRes === 3 ? (
        <div className="res-box">
          <Result {...resultProps} />
        </div>
      ) : null}
    </Modal>
  );
}
export default UploadModal;
